// linked list: 链表

#include "node.h"
#include <stdio.h>
#include <stdlib.h>

typedef struct _list
{
    int size;
    Node* head;
    Node* tail;
} List;

void add(List* pList, int number);
void print(const List* pList);

int main(int argc, char const *argv[])
{
    List list;
    list.head = list.tail = NULL;
    int number;
    do
    {
        scanf("%d", &number);
        if (number != -1)
        {
            add(&list, number);
        }
    } while (number != -1);
    
    print(&list);

    // 搜索
    scanf("%d", &number);
    Node* p;
    int isFound = 0;
    for (p = list.head; p; p = p->next)
    {
        if (p->value == number)
        {
            printf("Found it!\n");
            isFound = 1;
            break;
        }
    }
    if (!isFound)
    {
        printf("404 Not Found!\n");
    }

    // 删除
    Node* q;
    for (q = NULL, p = list.head; p; q = p, p = p->next)
    {
        if (p->value == number)
        {
            // 当用到的指针出现在 -> 左边时, 要判断指针能否为NULL!
            if (q)
            {
                q->next = p->next;
            }
            free(p);
            break;
        }
    }

    // 链表的清除
    for (p = head; p; p = q)
    {
        q = p->next;
        free(p);
    }

    return 0;
}

void add(List* pList, int number)
{
    // add to linked list
    Node* p = (Node*)malloc(sizeof(Node));
    p->value = number;
    p->next = NULL;
    
    if (pList->tail)
    {
        pList->tail->next = p;
        pList->tail = p;
    }
    else
    {
        pList->head = pList->tail = p;
    }
}

void print(const List* pList)
{
    Node* p;
    for (p = pList->head; p; p = p->next)
    {
        printf("%d\t", p->value);
    }
    printf("\n");
}